<?php

namespace App\Trip\Wechat\Account;

use App\Jobs\Logs\ProcessUserLoginLog;
use App\Models\Logs\UserLoginLog\Repositories\Interfaces\UserLoginLogRepositoryInterface;
use App\Models\User\User;
use App\Trip\Traits\Response;
use Carbon\Carbon;
use Jenssegers\Agent\Facades\Agent;

class WechatLoginResp
{
    use Response;

    private User             $user;
    private string           $token;
    private string|int|float $expired_at;

    public function __construct(User $user)
    {
        $this->user = $user;
        $this->generateToken();

    }

    private function generateToken(): void
    {
        $this->token      = auth()->fromuser($this->user);
        $this->expired_at = Carbon::now()->addMinutes(config('jwt.ttl'))->timestamp;
        $logRepo          = app(UserLoginLogRepositoryInterface::class);
        ProcessUserLoginLog::dispatchIf(!$logRepo->isRecorded($this->user->getUserId()), [
            'user_id'    => $this->user->getUserId(),
            'device'     => Agent::device(),
            'user_agent' => Agent::getUserAgent(),
            'created_at' => Carbon::now()->toDateTimeString(),
        ]);
    }

    public function login_success()
    {
        $mobile     = $this->user->phone;
        $info       = $this->user->only([
            "phone",
            "nickname",
            "avatar",
        ]);
        $token      = $this->token;
        $expired_at = $this->expired_at;
        $this->setHeaders([
            'Authorization' => 'Bearer '.$this->token,
            'ExpiredAt'     => $this->expired_at,
        ]);
        return $this->success('success', compact('mobile', 'token', 'expired_at', 'info'));
    }
}